package gui;

import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JLabel;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Graphics;

import javax.swing.JSeparator;
import javax.swing.JButton;
import javax.swing.border.BevelBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import messagesPacks.BookSubjectMessage;
import messagesPacks.SubscriberSearchBookMassege;
import messagesPacks.TOCMessage;

import Entity.Book;

import controllers.*;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class SearchBooksUI extends JPanel
{
	private static final long serialVersionUID = 1L;
	
	JTextField searchByBookNameFiled;
	JTextField searchByBookAuthorFiled;
	JTextField freeTextFiled;
	JLabel cantOrderLabel;
	JLabel lblByNameLabel;
	JLabel lblByAuthorLabel;
	JLabel lblBySubjectLabel;
	JLabel lblNewLabel_3;
	JSeparator separator;
	JLabel lblTitleLabel;
	JButton btnExitButton;
    JButton btnLoginButton;
    JButton btnSearch;
    JButton btnViewToc;
    String selectedISBN = null;
    
    private JLabel backgroundlabel;
    public JComboBox <String> subjectcomboBox;
    
    Hashtable<Integer,String > BookSubjects = new Hashtable <Integer,String>();
    String selectedBookSubject ;
    String selectedBookSubjectID ;

    public SimpleTable searchResultTable ;
    
	private JButton btnClear;
	
    int numOfCopiesAvailable;
    int totalNumOfCopiesForBook;
 
    SubscriberSearchBookMassege result_search_msg  ;
    
    SubscriberUIP subUIP = null ;
    SubscriberSearchBookUI searchBookPanel = null; 

	/**
	 * 
	 * Creates the SearchBooks panel.
	 * @author Tali
	 */
	public SearchBooksUI()
	{
		super();
		initialize();
		subUIP = new SubscriberUIP();
	}
	private void initialize()
	{
		this.setSize(OBLSettings.pane2Size[0],OBLSettings.pane2Size[1]);
		setLayout(null);
		searchByBookNameFiled = new JTextField();
		searchByBookNameFiled.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
		searchByBookNameFiled.setBounds(227, 70, 265, 24);
		searchByBookNameFiled.setFont(new Font("Tahoma", Font.PLAIN, 15));
		add(searchByBookNameFiled);
		searchByBookNameFiled.setColumns(10);
		
		searchByBookAuthorFiled = new JTextField();
		searchByBookAuthorFiled.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
		searchByBookAuthorFiled.setBounds(227, 123, 265, 24);
		searchByBookAuthorFiled.setFont(new Font("Tahoma", Font.PLAIN, 15));
		add(searchByBookAuthorFiled);
		searchByBookAuthorFiled.setColumns(10);
		
		freeTextFiled = new JTextField();
		freeTextFiled.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
		freeTextFiled.setBounds(227, 213, 265, 24);
		freeTextFiled.setFont(new Font("Tahoma", Font.PLAIN, 15));
		add(freeTextFiled);
		freeTextFiled.setColumns(10);
		
		lblByNameLabel = new JLabel("Search Book by name :");
		lblByNameLabel.setBounds(51, 70, 166, 24);
		lblByNameLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
		add(lblByNameLabel);
		
		lblByAuthorLabel = new JLabel("Search Book by Author :");
		lblByAuthorLabel.setBounds(51, 123, 166, 24);
		lblByAuthorLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
		add(lblByAuthorLabel);
		
		lblBySubjectLabel = new JLabel("Search Book by subject :");
		lblBySubjectLabel.setBounds(51, 170, 166, 24);
		lblBySubjectLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
		add(lblBySubjectLabel);
		
		lblNewLabel_3 = new JLabel("Free text search :");
		lblNewLabel_3.setBounds(51, 212, 152, 24);
		lblNewLabel_3.setFont(new Font("Tahoma", Font.PLAIN, 14));
		add(lblNewLabel_3);
		
		separator = new JSeparator();
		separator.setBounds(-26, 57, 826, 24);
		add(separator);
		
		lblTitleLabel = new JLabel("OBL Search Books");
		lblTitleLabel.setBounds(276, -1, 247, 60);
		lblTitleLabel.setFont(new Font("Tahoma", Font.BOLD, 20));
		add(lblTitleLabel);
		
		btnLoginButton = new JButton("Login");
		btnLoginButton.setBounds(614, 11, 83, 41);
		btnLoginButton.setFont(new Font("Tahoma", Font.BOLD, 15));
		add(btnLoginButton);
		
		btnExitButton = new JButton("Exit");
		btnExitButton.setBounds(707, 11, 83, 41);
		btnExitButton.setFont(new Font("Tahoma", Font.BOLD, 15));
		add(btnExitButton);
		
		btnSearch = new JButton("Search");
		btnSearch.setBounds(351, 255, 97, 41);
		
		btnViewToc = new JButton("View TOC");
		btnViewToc.setFont(new Font("Tahoma", Font.PLAIN, 14));
		btnViewToc.setEnabled(false);
		btnViewToc.setBounds(652, 255, 97, 41);
		btnViewToc.setVisible(true);
		add(btnViewToc);
	
		btnSearch.setFont(new Font("Tahoma", Font.PLAIN, 15));
		add(btnSearch);
	
		subjectcomboBox = new JComboBox<String>();
		subjectcomboBox.setBounds(227, 173, 265, 26);
		subjectcomboBox.setFont(new Font("Tahoma", Font.PLAIN, 13));
		add(subjectcomboBox);
		this.selectedBookSubject = ("");
		this.selectedBookSubjectID = (""); 
		 
		 
		Object ColNames[] = { "ISBN", "Book Name", "Author","Edition" ,"Publish Year","Description","Location","Copies","Wanted" };
		searchResultTable = new SimpleTable(null, ColNames, 10, 328, 780, 198);
	    add(searchResultTable.tblScrollPane,BorderLayout.CENTER);
			
		btnClear = new JButton("Clear");
		btnClear.setFont(new Font("Tahoma", Font.PLAIN, 15));
		btnClear.setBounds(51, 255, 97, 41);
		add(btnClear);
		
		cantOrderLabel = new JLabel("");
		cantOrderLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
		cantOrderLabel.setBounds(10, 538, 331, 26);
		add(cantOrderLabel);
		
	    backgroundlabel = new JLabel(OBLSettings.IMG_SUBSCRIBER_SEARCH_BOOK_BACKGROUND);
		backgroundlabel.setBounds(0, 57, 800, 600);
		add(backgroundlabel);

		freeTextFiled.addActionListener(new ActionListener()
		{
	        public void actionPerformed(ActionEvent e)
	        {
	                btnSearch.doClick();
	        }  
	    });

		 searchByBookAuthorFiled.addActionListener(new ActionListener()
		{
	        public void actionPerformed(ActionEvent e)
	        {
	                btnSearch.doClick();
	        }  
	    });
		
		 searchByBookNameFiled.addActionListener(new ActionListener()
		{
	        public void actionPerformed(ActionEvent e)
	        {
	                btnSearch.doClick();
	        }  
	    });

	//================================================================		
	//          Action Listeners
	//================================================================
		//login button in searchBookPanel	
		btnLoginButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent arg0)
			{	
				
				 searchByBookNameFiled.setText("");
				 searchByBookAuthorFiled.setText("");
				 freeTextFiled.setText("");
				 searchResultTable.model.setRowCount(0);	 
				 subjectcomboBox.setSelectedItem("Please select subject...");
				 selectedBookSubject = ("Please select subject...");
				 selectedBookSubjectID =("0");
				 WelcomeUI.wui.switchPanel("OBL System - Login ", WelcomeUI.wui.getLoginPanel(),OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]);

			}
		});
		    
		
		
		
		
		btnClear.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent arg0)
			{
				 searchByBookNameFiled.setText("");
				 searchByBookAuthorFiled.setText("");
				 freeTextFiled.setText("");
				 searchResultTable.model.setRowCount(0);	 
				 subjectcomboBox.setSelectedItem("Please select subject...");
				 selectedBookSubject = ("Please select subject...");
				 selectedBookSubjectID =("0");
				 btnViewToc.setEnabled(false);
				 selectedISBN = null;
			}
		});
		
	//================================================================		
		btnSearch.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent e)
			{	
				
				searchResultTable.model.setRowCount(0);
				
				result_search_msg = subUIP.subscriberSearchBook( searchByBookNameFiled.getText() , searchByBookAuthorFiled.getText() , selectedBookSubject 
																			,selectedBookSubjectID, freeTextFiled.getText() );
				if(result_search_msg == null)
					JOptionPane.showMessageDialog( WelcomeUI.wui, "Please fill at least one of the searching filleds" ,"Warning",JOptionPane.WARNING_MESSAGE);
				
				else 
				  if(result_search_msg.getQueryResult() == 0)
					 JOptionPane.showMessageDialog( WelcomeUI.wui, "There was an error in search, please try again ","Warning",JOptionPane.WARNING_MESSAGE);
				else
				 {
					if(result_search_msg.result_books.isEmpty())
						JOptionPane.showMessageDialog( WelcomeUI.wui, " No matching books found ","",JOptionPane.INFORMATION_MESSAGE);	
					else
					{	
						//JOptionPane.showMessageDialog( WelcomeUI.wui, " search succeed ","Done",JOptionPane.INFORMATION_MESSAGE);
						String wanted ; 
						for(Book var : result_search_msg.result_books)
						{
							if(var.getWanted().equalsIgnoreCase("0"))
								wanted = "no" ;
							else
								wanted = "yes" ;
						 
							searchResultTable.model.addRow(new Object[] {var.getISBN(),var.getBookName(),var.getBookAuthor(),var.getEdition(),var.getPublishYear()
														,var.getDescription(),var.getShelfLocation(),var.getBookNumOfCopies(),wanted});
						 
							//searchResultTable.table.repaint();
						
						}
				
						
					}
				 }
	
			}
		});
	
	//================================================================		
	
	subjectcomboBox.addActionListener(new ActionListener()
	{
		public void actionPerformed(ActionEvent e)
		{
			 JComboBox cb = (JComboBox)e.getSource();
			 Set set = BookSubjects.entrySet();
			 Iterator it = set.iterator();
			 
			    while (it.hasNext()) 
			    {
			        Map.Entry entry = (Map.Entry) it.next();
			        if(entry.getValue().equals(cb.getSelectedItem()))
			        { 
			    	  System.out.println(entry.getKey() + " : " + entry.getValue());
			    	  selectedBookSubject = entry.getValue().toString();
			    	  selectedBookSubjectID =  entry.getKey().toString();
			    	  
			        }
			    }
		 }
			  
	 });
	//================================================================
	
	searchResultTable.table.getSelectionModel().addListSelectionListener(new ListSelectionListener() 
	{
		public void valueChanged(ListSelectionEvent e) 
		{
			JTable table = searchResultTable.table;
	
			if(table.getRowCount() > 0)	
			{	
				btnViewToc.setEnabled(true);
				int row = searchResultTable.table.getSelectedRow();

				if(row>=0)
				{ 
					
		    		Object[] rowData = new Object[table.getColumnCount()];  
		    		for (int i = 0; i < table.getColumnCount(); i++) 
		    		{  
				         rowData[i] = table.getValueAt(row, i);  
		    		} 
		    		selectedISBN = rowData[0].toString();
		    		numOfCopiesAvailable = Integer.parseInt(rowData[7].toString());
				}
			}
		}
		
	});
	
	//===================================================================
	btnViewToc.addActionListener(new ActionListener() 
	{
		public void actionPerformed(ActionEvent arg0) 
		{
			// Request TOC file from the server
			System.out.println("ISBN selected = " );
			if (selectedISBN != null)
			{
				TOCMessage toc_result = SubscriberUIP.requestTOC(selectedISBN);
				if (toc_result.getSuccess())
				{
					JOptionPane.showMessageDialog( WelcomeUI.wui,"TOC Saved to your local directory!","View TOC",JOptionPane.INFORMATION_MESSAGE);
				}
				else
				{
					JOptionPane.showMessageDialog( WelcomeUI.wui,"Sorry, TOC doesn't exist for this book.","View TOC",JOptionPane.WARNING_MESSAGE);
				}
			}
			else
				JOptionPane.showMessageDialog( WelcomeUI.wui,"Error! No Book selected!","View TOC",JOptionPane.WARNING_MESSAGE);
		}
	});
	//===================================================================
		
	}//initialize
	
	
	public void loadAllsubjectsToSearchComboBox()
	{
	    BookSubjectMessage BookSubject_msg ;
	    BookSubject_msg = subUIP.getSubjectsOfBooks();
	    
	 //load the books subjects in to the combobox 
	    BookSubjects.put(0,"Please select subject...");
	    BookSubjects.putAll( BookSubject_msg.getBookSubjects());
	    
	    Enumeration e1 = BookSubject_msg.getBookSubjects().elements();
	    subjectcomboBox.addItem("Please select subject...");
	    while ( e1.hasMoreElements() )
	    	subjectcomboBox.addItem( (String)e1.nextElement() );
		
	}
	//===================================================================	
	//            	Getters & Setters
	//===================================================================	
	public String getSearchByBookNameFiled()
	{
		return searchByBookNameFiled.getText();
	}
	
	
	
	public void setSearchByBookNameFiled(JTextField searchByBookNameFiled)
	{
		this.searchByBookNameFiled = searchByBookNameFiled;
	}
	
	
	
	public String getSearchByBookAuthorFiled() 
	{
		return searchByBookAuthorFiled.getText();
	}
	
	
	
	public void setSearchByBookAuthorFiled(JTextField searchByBookAuthorFiled)
	{
		this.searchByBookAuthorFiled = searchByBookAuthorFiled;
	}

	public String getFreeTextFiled() 
	{
		return freeTextFiled.getText();
	}
	
	public void setFreeTextFiled(JTextField freeTextFiled) 
	{
		this.freeTextFiled = freeTextFiled;
	}
	
	
	public String getSelectedBookSubject()
	{
		return selectedBookSubject;
	}
	
	
	
	public void setSelectedBookSubject(String selectedBookSubject) 
	{
		this.selectedBookSubject = selectedBookSubject;
	}
	
	
	
	public String getSelectedBookSubjectID() 
	{
		return selectedBookSubjectID;
	}
	
	
	
	public void setSelectedBookSubjectID(String selectedBookSubjectID) 
	{
		this.selectedBookSubjectID = selectedBookSubjectID;
	}
	
	
	public void paintComponent(Graphics g) 
	{
		g.drawImage((OBLSettings.IMG_DEFAULT_BACKGROUND).getImage(), 0, 0, OBLSettings.pane2Size[0], OBLSettings.pane2Size[1],null);
		
	}
	
	
}//SearchBooksUI
